package de.haw.shc.Action;

import android.os.AsyncTask;
import android.util.Log;
import de.haw.shc.Interfaces.Conncetion;
import de.haw.shc.Message.SHC_Message;
import de.livingplace.messaging.android.AndroidPublisher;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * User: mizus
 * Date: 08.05.13
 * Time: 13:35
 * To change this template use File | Settings | File Templates.
 */

public class Action_Impl implements Conncetion {

    private Action_Impl(){}

    private static Action_Impl instance;

    public static Action_Impl getInstance(){
        if(instance == null) instance = new Action_Impl();
        return  instance;
    }

    ///////////////////////////////////
    // actions
    //////////////////////

    @Override
    public void iniAction(JSONObject obj, String Typ){
        sendMessage(new SHC_Message(obj, Typ));
    }

    private void sendMessage(SHC_Message message){
        String[] params = new String[5];
        params[0] =  ip;                                             // IP des Proxy Servers
        params[1] =  port;
        params[2] = message.getTopic();                            // Topic für die Licht, Gardinen, Rolosteuerung
        params[3] = message.getTyp();

        params[4] = message.getMessage();

        Log.d("-------->: ", ""+ Arrays.asList(params).toString());
        sendMessageToProxy smtp = new sendMessageToProxy();
        smtp.execute(params);
    }


    private class sendMessageToProxy extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            try{
                AndroidPublisher androidPublisher = new AndroidPublisher(params[0], Integer.valueOf(params[1]),
                        params[2]);
                androidPublisher.setMessage(params[4]);

                if(params[3].equals("Topic"))   androidPublisher.publishToTopic();
                else androidPublisher.publishToQueue();

            } catch (IOException e){
                Log.e("Publisher", "Can´t publish the message");
                e.printStackTrace();
            }
            return null;
        }
    }




}
